package cn.jishiyu11.xeqb.utils

import android.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec


/**
 * Created by jsy_zj on 2018-03-07.
 * AES  加密
 */

class AESUtils {
    companion object {

        private val IV_STRING = "A-16-Byte-String"
        private val charset = "UTF-8"

        /**
         * 加密
         * @param key  秘钥
         * @param dataString  String 字符串
         */
        fun encrypt(key: String, dataString: String): String {
            var result: ByteArray? = null
            var content = ""
            try {
                val rawkey = key.toByteArray(charset(charset))
                result = doCode(rawkey, dataString.toByteArray(charset(charset)), 1)
                content = Base64.encodeToString(result, Base64.NO_WRAP)
            } catch (var4: Exception) {
                var4.printStackTrace()
            }

            return content
        }

        /**
         * 解密
         * @param key   秘钥
         * @param data   加密的数据
         */
        fun decrypt(key: String, data: String): String? {
            val decoder = Base64.decode(data, Base64.NO_WRAP)
            try {
                val rawKey = key.toByteArray(charset(charset))
                val result = doCode(rawKey, decoder, 2)

                return String(result, charset(charset))
            } catch (var6: Exception) {
                println(var6)
                return null
            }

        }

        @Throws(Exception::class)
        private fun doCode(key: ByteArray, data: ByteArray, type: Int): ByteArray {
            val skeySpec = SecretKeySpec(key, "AES")
            val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
            val initParam = IV_STRING.toByteArray(charset(charset))
            val ivParameterSpec = IvParameterSpec(initParam)
            if (type == 1) {
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec)
            } else {
                cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec)
            }
            return cipher.doFinal(data)
        }
    }


}